package com.bwda.dsrs.filecenter.controller;

import com.bwda.dsrs.filecenter.annotations.NeedRole;
import com.bwda.dsrs.filecenter.api.OrgServiceApi;
import com.bwda.dsrs.filecenter.api.clientappversion.datadict.DatadictQueryForm;
import com.bwda.dsrs.filecenter.api.clientappversion.datadict.DatadictVo;
import com.bwda.dsrs.filecenter.api.clientappversion.group.GroupQueryForm;
import com.bwda.dsrs.filecenter.api.clientappversion.group.GroupVo;
import com.bwda.dsrs.filecenter.api.clientappversion.org.OrgCreateForm;
import com.bwda.dsrs.filecenter.api.clientappversion.org.OrgTreeForm;
import com.bwda.dsrs.filecenter.api.clientappversion.user.UserForm;
import com.bwda.dsrs.filecenter.api.clientappversion.user.UserPo;
import com.bwda.dsrs.filecenter.api.clientappversion.user.UserQueryForm;
import com.bwda.dsrs.filecenter.aspect.LogTypeEnum;
import com.bwda.dsrs.filecenter.aspect.Loggable;
import com.bwda.dsrs.filecenter.domain.BusinessConstants;
import com.bwda.dsrs.filecenter.domain.condition.strategyfilelevel.StrategyFilelevelCondition;
import com.bwda.dsrs.filecenter.domain.condition.strategyopttype.StrategyOpttypeCondition;
import com.bwda.dsrs.filecenter.domain.condition.strategysituation.StrategySituationCondition;
import com.bwda.dsrs.filecenter.domain.condition.strategytarget.StrategyTargetCondition;
import com.bwda.dsrs.filecenter.domain.exception.BusinessServiceException;
import com.bwda.dsrs.filecenter.domain.form.strategycontrol.StrategyForm;
import com.bwda.dsrs.filecenter.domain.form.strategysituation.StrategySituationCreateForm;
import com.bwda.dsrs.filecenter.domain.form.strategysituation.StrategySituationQueryForm;
import com.bwda.dsrs.filecenter.domain.form.strategysituation.StrategySituationUpdateForm;
import com.bwda.dsrs.filecenter.domain.po.strategyfilelevel.StrategyFilelevelPo;
import com.bwda.dsrs.filecenter.domain.po.strategyopttype.StrategyOpttypePo;
import com.bwda.dsrs.filecenter.domain.po.strategysituation.StrategySituationPo;
import com.bwda.dsrs.filecenter.domain.po.strategytarget.StrategyTargetPo;
import com.bwda.dsrs.filecenter.domain.vo.strategyfilelevel.StrategyFilelevelVo;
import com.bwda.dsrs.filecenter.domain.vo.strategyopttype.StrategyOpttypeVo;
import com.bwda.dsrs.filecenter.domain.vo.strategysituation.StrategySituationVo;
import com.bwda.dsrs.filecenter.domain.vo.strategytarget.StrategyTargetVo;
import com.bwda.dsrs.filecenter.service.StrategyFilelevelService;
import com.bwda.dsrs.filecenter.service.StrategyOpttypeService;
import com.bwda.dsrs.filecenter.service.StrategySituationService;
import com.bwda.dsrs.filecenter.service.StrategyTargetService;
import com.bwda.dsrs.base.centerbase.response.CentreCutPageResponse;
import com.bwda.dsrs.base.centerbase.response.CentreListResponse;
import com.bwda.dsrs.base.centerbase.response.ResponseEntity;
import com.bwda.dsrs.base.util.CopyUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.validation.Valid;
import java.util.*;

/**
 *	策略管理--操作黑名单（场景策略）--控制层
 *
 * @author zhangyinmei
 * @date 2019年4月28日
 */
@RestController
@RequestMapping("/b/strategysituation")
@Api(value = "/b/strategysituation", tags = "操作黑名单")
public class StrategySituationController extends BaseController {
	private static final Logger logger = LoggerFactory.getLogger(StrategySituationController.class);
	@Autowired
	private StrategySituationService strategySituationService;

	@Autowired
	private StrategyTargetService strategyTargetService;

	@Autowired
	private StrategyOpttypeService strategyOpttypeService;

	@Autowired
	private StrategyFilelevelService strategyFilelevelService;

	@Resource
	private OrgServiceApi orgServiceApi;

	/**
	 * 查询自定义组织树
	 *
	 * @return
	 * @throws BusinessServiceException
	 */
	@NeedRole("secadminrole")
	@ApiOperation(value = "查询自定义组织树", notes = "查询组织树", httpMethod = "GET")
	@Loggable(descp = "查询自定义组织树",type = LogTypeEnum.QUERY,include = "")
	@RequestMapping(value = "/queryDIYOrgTree", method = {RequestMethod.GET, RequestMethod.POST})
	public ResponseEntity<CentreCutPageResponse<GroupVo>> queryDiyOrgTree(@ModelAttribute @Valid StrategyForm form){
		logger.info("调用systemservice查询自定义组织树。");
		GroupQueryForm form1 = 	new GroupQueryForm();
		form1.setPageNum(form.getPageNum());
		form1.setPageSize(form.getPageSize());
		ResponseEntity<CentreCutPageResponse<GroupVo>> groupEntity = orgServiceApi.queryGroupPageList(form1);
		if(form.getStrategyId()==null){
			return groupEntity;
		}
		List<GroupVo> groupVoList = null;
		if(groupEntity==null){
			return null;
		}else {
			if(groupEntity.getData()==null){
				return null;
			}
			groupVoList = groupEntity.getData().getDataList();
			StrategyTargetCondition stcondition = new StrategyTargetCondition();
			stcondition.setStrategyId(form.getStrategyId());
			stcondition.setUserType(BusinessConstants.NumberConstant.TWO);
			List<StrategyTargetPo> stlist = strategyTargetService.queryList(stcondition);
			for (StrategyTargetPo strategyTargetPo : stlist) {
				for (GroupVo groupVo : groupVoList) {
					if (Long.parseLong(strategyTargetPo.getUserCode()) == groupVo.getId()) {
						groupVo.setCheckedFlag(true);
						break;
					}
				}
			}
		}
		groupEntity.getData().setDataList(groupVoList);
		return groupEntity;
	}

	/**
	 * 查询组织树
	 *
	 * @return
	 * @throws BusinessServiceException
	 */
	@NeedRole("secadminrole")
	@ApiOperation(value = "查询组织树", notes = "查询组织树", httpMethod = "GET")
	@Loggable(descp = "查询组织树",type = LogTypeEnum.QUERY,include = "")
	@RequestMapping(value = "/queryOrgTree", method = {RequestMethod.GET, RequestMethod.POST})
	public ResponseEntity<List<OrgTreeForm>> queryOrgTree(@ModelAttribute @Valid StrategyForm form){
		logger.info("调用systemservice查询组织树。");
		List<OrgTreeForm> treeList = orgServiceApi.queryOrgTree();
		if(form.getStrategyId()==null){
			return getSuccessResult(treeList);
		}
		if(null == treeList || treeList.isEmpty()){
			return null;
		}else {
			StrategyTargetCondition stcondition = new StrategyTargetCondition();
			stcondition.setStrategyId(form.getStrategyId());
			stcondition.setUserType(BusinessConstants.NumberConstant.ONE);
			List<StrategyTargetPo> stlist = strategyTargetService.queryList(stcondition);
			for (StrategyTargetPo strategyTargetPo : stlist) {
				for (OrgTreeForm orgTreeForm : treeList) {
					if (StringUtils.equals(strategyTargetPo.getUserCode(),String.valueOf(orgTreeForm.getId()))) {
						orgTreeForm.setCheckedFlag(true);
						break;
					}
				}
			}
		}
		return getSuccessResult(treeList);
	}

	/**
	 * 根据组织ID查询用户列表
	 *
	 * @param form
	 * @return
	 * @throws BusinessServiceException
	 */
	@NeedRole("secadminrole")
	@ApiOperation(value = "根据组织ID查询用户列表(带分页)", notes = "查询用户表列表(带分页)", httpMethod = "GET")
	@Loggable(descp = "根据组织ID查询用户列表(带分页)",type = LogTypeEnum.QUERY,include = "")
	@RequestMapping(value = "/queryUserList", method = {RequestMethod.GET, RequestMethod.POST})
	public ResponseEntity<CentreCutPageResponse<UserPo>> queryUserList(@ModelAttribute @Valid StrategyForm form) throws BusinessServiceException {
		logger.info("调用systemservice根据组织ID查询用户列表(带分页)。");
		UserQueryForm userQueryForm = new UserQueryForm();
		userQueryForm.setOrgId(form.getOrgId());
		userQueryForm.setPageSize(form.getPageSize());
		userQueryForm.setPageNum(form.getPageNum());
		//需要标记出已经绑定的用户
		ResponseEntity<CentreCutPageResponse<UserPo>> userEntity = orgServiceApi.queryUserPageList(userQueryForm);
		if(form.getStrategyId()==null){
			return userEntity;
		}
		List<UserPo> userPoList = null;
		if(userEntity==null){
			return null;
		}else {
			if(userEntity.getData()==null){
				return null;
			}
			userPoList = userEntity.getData().getDataList();
			StrategyTargetCondition stcondition = new StrategyTargetCondition();
			stcondition.setStrategyId(form.getStrategyId());
			stcondition.setUserType(BusinessConstants.NumberConstant.ZERO);
			List<StrategyTargetPo> stlist = strategyTargetService.queryList(stcondition);
			for (StrategyTargetPo strategyTargetPo : stlist) {
				for (UserPo userPo : userPoList) {
					if (StringUtils.equals(strategyTargetPo.getUserCode(), userPo.getUserCode())) {
						userPo.setCheckedFlag(true);
						break;
					}
				}
			}
		}
		userEntity.getData().setDataList(userPoList);
		return userEntity;
	}


	/**
	 * 查询操作黑名单列表(带分页)
	 *
	 * @param form
	 * @return
	 * @throws BusinessServiceException
	 */
	@NeedRole("secadminrole")
	@ApiOperation(value = "查询操作黑名单列表(带分页)",notes = "询操作黑名单列表(带分页)",httpMethod = "GET")
	@Loggable(descp = "查询操作黑名单列表(带分页)",type = LogTypeEnum.QUERY,include = "")
	@RequestMapping(value = "/queryPageList", method = {RequestMethod.GET, RequestMethod.POST})
	public ResponseEntity<CentreCutPageResponse<StrategySituationVo>> queryPageList(@ModelAttribute@Valid StrategySituationQueryForm form) throws BusinessServiceException {
		logger.info("查询操作黑名单列表(带分页)。");
		StrategySituationCondition condition = this.getConditionByQueryForm(form);
		List<StrategySituationVo> voList = new ArrayList<>();
		condition.setDelFlag(BusinessConstants.DelFlag.NOT_DELETED);
		int count = strategySituationService.queryCount(condition);
		if (count > BusinessConstants.NumberConstant.ZERO) {
			List<StrategySituationPo> poList = strategySituationService.queryList(condition);
			voList = CopyUtil.transfer(poList, StrategySituationVo.class);
		}
		return getSuccessResult(getPageResponse(form, count, queryRelTableInfo(voList)));
	}

	/**
	 * 获取含有关联表数据的场景策略集合场景策略集合
	 *
	 * @param voList : 场景策略集合
	 * @return  含有关联表数据的场景策略集合
	 */
	private  List<StrategySituationVo> queryRelTableInfo(List<StrategySituationVo> voList){
		//查询 3 张关联表的数据 遍历返回列表
		for(StrategySituationVo strategySituationVo : voList){
			//定义禁止对象集合
			List<StrategyTargetPo> strategyTargetPoList = new ArrayList<StrategyTargetPo>();
			//查询禁止对象列表
			StrategyTargetCondition strategyTargetCondition = new StrategyTargetCondition();
			//因为同一个策略同一种用户类型会对应多条数据，所以先根据场景策略ID查询出用户类型，再根据场景策略ID和用户类型，查询数据。
			strategyTargetCondition.setStrategyId(strategySituationVo.getId());
			List<StrategyTargetPo> stPoListByStrategyId = strategyTargetService.queryList(strategyTargetCondition);
			//获取已配置的用户类型，存放在set集合中
			Set<Integer> userTypeSet = new HashSet<Integer>();
			StringBuilder userCodeStr = new StringBuilder();
			if(stPoListByStrategyId != null && !stPoListByStrategyId.isEmpty()){
				for(StrategyTargetPo stPo : stPoListByStrategyId){userTypeSet.add(stPo.getUserType()); }
				//根据场景策略ID和用户类型，查询数据
				for(Integer userType : userTypeSet){
					//定义集合，存放用户编码
					List<String> userCodeList = new ArrayList<String>();
					strategyTargetCondition.setUserType(userType);
					List<StrategyTargetPo> stPoListByIdAndType = strategyTargetService.queryList(strategyTargetCondition);
					for(StrategyTargetPo stPo : stPoListByIdAndType){
						userCodeList.add(stPo.getUserCode());
						if(userCodeStr.length()==0){
							userCodeStr.append(stPo.getUserCode());
						}else{
							userCodeStr.append(",").append(stPo.getUserCode());
						}
					}
					if((int)userType == BusinessConstants.NumberConstant.ZERO){
						//查询人员信息
						List<UserForm> userFormList = orgServiceApi.queryUserByCode(userCodeStr.toString());
						//定义禁止对象实体，用于存放返回的实体
						StrategyTargetPo strategyTargetPo = new StrategyTargetPo();
						strategyTargetPo.setStrategyId(strategySituationVo.getId());
						strategyTargetPo.setUserType(userType);
						strategyTargetPo.setUserCodeList(userCodeList);
						strategyTargetPo.setObjectList(userFormList);
						strategyTargetPoList.add(strategyTargetPo);
					}else if((int)userType == BusinessConstants.NumberConstant.ONE){


						//查询组织信息
						List<OrgCreateForm> orgCreateFormList = orgServiceApi.queryOrgById(userCodeStr.toString());
						//定义禁止对象实体，用于存放返回的实体
						StrategyTargetPo strategyTargetPo = new StrategyTargetPo();
						strategyTargetPo.setStrategyId(strategySituationVo.getId());
						strategyTargetPo.setUserType(userType);
						strategyTargetPo.setUserCodeList(userCodeList);
						strategyTargetPo.setObjectList(orgCreateFormList);
						strategyTargetPoList.add(strategyTargetPo);

					}else if((int)userType ==  BusinessConstants.NumberConstant.TWO){

						//查询自定义组信息

						List<Integer> userCodeListToLong = new ArrayList<>();
						for(String str : userCodeList){userCodeListToLong.add(Integer.parseInt(str)); }
						GroupQueryForm groupQueryForm = new GroupQueryForm();
						groupQueryForm.setIdList(userCodeListToLong);
						ResponseEntity<CentreListResponse<GroupVo>> groupVoListResponse =  orgServiceApi.queryGroupList(groupQueryForm);
						//定义禁止对象实体，用于存放返回的实体
						StrategyTargetPo strategyTargetPo = new StrategyTargetPo();
						strategyTargetPo.setStrategyId(strategySituationVo.getId());
						strategyTargetPo.setUserType(userType);
						strategyTargetPo.setUserCodeList(userCodeList);
						if(groupVoListResponse.getData() != null){
							strategyTargetPo.setObjectList(groupVoListResponse.getData().getDataList());
						}
						strategyTargetPoList.add(strategyTargetPo);


					}
				}
			}
			List<StrategyTargetVo> strategyTargetVoList = CopyUtil.transfer(strategyTargetPoList, StrategyTargetVo.class);
			//获取字典名称
			toGetUserTypeDatadictName(strategyTargetVoList);
			strategySituationVo.setStrategyTargetVoList(strategyTargetVoList);
			//查询禁止文件等级列表
			StrategyFilelevelCondition strategyFilelevelCondition = new StrategyFilelevelCondition();
			strategyFilelevelCondition.setStrategyId(strategySituationVo.getId());
			List<StrategyFilelevelPo> strategyFilelevelPoList = strategyFilelevelService.queryList(strategyFilelevelCondition);
			List<StrategyFilelevelVo> strategyFilelevelVoList = CopyUtil.transfer(strategyFilelevelPoList, StrategyFilelevelVo.class);
			//获取字典名称
			toGetFileLevelDatadictName(strategyFilelevelVoList);
			strategySituationVo.setStrategyFilelevelVoList(strategyFilelevelVoList);
			//查询禁止操作类型列表
			StrategyOpttypeCondition strategyOpttypeCondition = new StrategyOpttypeCondition();
			strategyOpttypeCondition.setStrategyId(strategySituationVo.getId());
			List<StrategyOpttypePo> strategyOpttypePoList = strategyOpttypeService.queryList(strategyOpttypeCondition);
			List<StrategyOpttypeVo> strategyOpttypeVoList = CopyUtil.transfer(strategyOpttypePoList, StrategyOpttypeVo.class);
			//获取字典名称
			toGetOptTypeDatadictName(strategyOpttypeVoList);
			strategySituationVo.setStrategyOpttypeVoList(strategyOpttypeVoList);
		}
		return voList;
	}



	/**
	 * 获取用户类型字典名称
	 *
	 * @param strategyTargetVoList
	 * @return
	 * @throws BusinessServiceException
	 */
	private List<StrategyTargetVo> toGetUserTypeDatadictName(List<StrategyTargetVo> strategyTargetVoList){
		//遍历集合，根据“数据字典类别code”和“字典值”获取字典名称
		for(StrategyTargetVo stVo : strategyTargetVoList){
			stVo.setUserTypeName(toGetDatadictName(BusinessConstants.USER_TYPE, stVo.getUserType()));
		}
		return strategyTargetVoList;
	}

	/**
	 * 获取文件等级字典名字
	 *
	 * @param strategyFilelevelVoList
	 * @return
	 * @throws BusinessServiceException
	 */
	private List<StrategyFilelevelVo> toGetFileLevelDatadictName(List<StrategyFilelevelVo> strategyFilelevelVoList){
		//遍历集合，根据“数据字典类别code”和“字典值”获取字典名称
		for(StrategyFilelevelVo sfVo : strategyFilelevelVoList){
			sfVo.setFileLevelName(toGetDatadictName(BusinessConstants.FILE_LEVEL, sfVo.getFileLevel()));
		}
		return strategyFilelevelVoList;
	}

	/**
	 * 获取操作类型字典名字
	 *
	 * @param strategyOpttypeVoList
	 * @return
	 * @throws BusinessServiceException
	 */
	private List<StrategyOpttypeVo> toGetOptTypeDatadictName(List<StrategyOpttypeVo> strategyOpttypeVoList) {

		//遍历集合，根据“数据字典类别code”和“字典值”获取字典名称
		for(StrategyOpttypeVo soVo : strategyOpttypeVoList){
			soVo.setOptTypeName(toGetDatadictName(BusinessConstants.NO_OPERATE_TYPE, soVo.getOptType()));
		}

		return strategyOpttypeVoList;
	}
	/**
	 * 获取字典名称
	 *
	 * @param dataDictTypeCode
	 * @param dataDictValue
	 * @return
	 * @throws BusinessServiceException
	 */
	private String toGetDatadictName(String dataDictTypeCode, Integer dataDictValue) {
		String result = "";
		//遍历集合，根据“数据字典类别code”和“字典值”获取字典名称
		DatadictQueryForm datadictQueryForm = new DatadictQueryForm();
		//设置数据字典类别code
		datadictQueryForm.setDataDictTypeCode(dataDictTypeCode);
		//设置字典值
		datadictQueryForm.setDataDictValue(dataDictValue.toString());
		logger.info("调用systemservice根据“数据字典类别code”和“字典值”获取字典名称。");
		//调用字典工具类
		ResponseEntity<CentreListResponse<DatadictVo>> responseEntity = orgServiceApi.queryDatadictList(datadictQueryForm);
		logger.info("调用结束。");

		List<DatadictVo> datadictVoList = responseEntity.getData().getDataList();
		if(datadictVoList != null && !datadictVoList.isEmpty()){
			result = datadictVoList.get(BusinessConstants.NumberConstant.ZERO).getDataDictName();
		}
		return result;
	}


	/**
	 * 新增操作黑名单
	 *
	 * @param form
	 * @return
	 * @throws BusinessServiceException
	 */
	@NeedRole("secadminrole")
	@ApiOperation(value = "新增操作黑名单",notes = "新增操作黑名单",httpMethod = "POST")
	@Loggable(descp = "新增操作黑名单",type = LogTypeEnum.CREATE,include = "")
	@RequestMapping(value = "/add", method = {RequestMethod.GET, RequestMethod.POST})
	public ResponseEntity<StrategySituationVo> add(@ModelAttribute@Valid StrategySituationCreateForm form) throws BusinessServiceException {
		StrategySituationPo po = CopyUtil.transfer(form, StrategySituationPo.class);
		//获取系统当前时间
		Date currentTime = new Date();
		//设置创建时间
		po.setCreateTime(currentTime);
		//设置更新时间
		po.setUpdateTime(currentTime);
		//设置是否删除为未删除
		po.setDelFlag(BusinessConstants.DelFlag.NOT_DELETED);
		Integer id = strategySituationService.queryId();
		po.setId(id);
		//新增场景策略
		strategySituationService.insert(po);
//		StrategySituationCondition condition =CopyUtil.transfer(po, StrategySituationCondition.class);
//		List<StrategySituationPo> list =strategySituationService.queryList(condition);
        //添加场景策略关联表数据
		strategySituationService.addRelTableInfo(po);
		StrategySituationVo vo = CopyUtil.transfer(po, StrategySituationVo.class);
		return getSuccessResult(vo);
	}

	/**
	 * 修改操作黑名单
	 *
	 * @param form
	 * @return
	 * @throws BusinessServiceException
	 */
	@NeedRole("secadminrole")
	@ApiOperation(value = "修改操作黑名单",notes = "修改操作黑名单",httpMethod = "POST")
	@Loggable(descp = "修改操作黑名单",type = LogTypeEnum.UPDATE,include = "")
	@RequestMapping(value = "/update", method = {RequestMethod.GET, RequestMethod.POST})
	public ResponseEntity update(@ModelAttribute@Valid StrategySituationUpdateForm form) throws BusinessServiceException {
		StrategySituationPo po = CopyUtil.transfer(form, StrategySituationPo.class);
		strategySituationService.update(po);
		//关联表数据，需要先删除，然后再新增
		//1.删除该场景策略的所有禁止对象
		strategyTargetService.delete(po.getId());
		//2.删除该场景策略的所有禁止操作类型
		strategyOpttypeService.delete(po.getId());
		//3.删除该场景策略的所有禁止文件等级
		strategyFilelevelService.delete(po.getId());
		//添加场景策略关联表数据
		strategySituationService.addRelTableInfo(po);
		return getSuccessResult();
	}
	@InitBinder
	public void initBinder(WebDataBinder binder) {
		// 设置List的最大长度
		binder.setAutoGrowCollectionLimit(10000);
	}
	/**
	 * 删除操作黑名单
	 *
	 * @param strategySituationIdList
	 * @return
	 * @throws BusinessServiceException
	 */
	@NeedRole("secadminrole")
	@ApiOperation(value = "删除操作黑名单",notes = "删除操作黑名单",httpMethod = "POST")
	@Loggable(descp = "删除操作黑名单",type = LogTypeEnum.DELETE,include = "")
	@RequestMapping(value = "/delete", method = {RequestMethod.GET, RequestMethod.POST})
	public ResponseEntity delete(@ApiParam(value = "ID", required = true)@RequestParam List<Integer> strategySituationIdList) throws BusinessServiceException {
		//物理删除
		StrategySituationPo po = new StrategySituationPo();
		po.setStrategySituationIdList(strategySituationIdList);
		po.setDelFlag(BusinessConstants.DelFlag.DELETED);
		strategySituationService.update(po);
		return getSuccessResult();
	}

	/**
	 * StrategySituationQueryForm转换为StrategySituationCondition
	 *
	 * @param form
	 * @return
	 */
	private StrategySituationCondition getConditionByQueryForm(StrategySituationQueryForm form) {
		StrategySituationCondition condition = CopyUtil.transfer(form, StrategySituationCondition.class);
		return condition;
	}

}